package org.vsg.common.pagination.web.taglibs;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.Tag;
import javax.servlet.jsp.tagext.TagSupport;

import org.vsg.common.pagination.Pagination;
import org.vsg.common.pagination.wrapper.GenericWebPaginationWrapper;
import org.vsg.common.pagination.wrapper.GenericWebSortByPaginationWrapper;

/**
 * JSP Tag Handler class
 *
 * @jsp.tag   name = "PrevPage"
 *            display-name = "Name for PrevPage"
 *            description = "Description for PrevPage"
 *            body-content = "empty"
 */
public class PrevPageTag extends TagSupport {

	private Logger logger = Logger.getLogger(this.getClass().toString());
	
	
	public int doStartTag() throws JspException {
		
		PaginationBarTag parent = (PaginationBarTag)this.findAncestorWithClass(this,PaginationBarTag.class);
		
		if (parent == null) {
			throw new JspException("Element \"PrevPage\" must set in the element \"paginationBar\"! ");
		}
		
		Pagination page = parent.getPagination();
		
		if (page.getTotalRecord() > 0 && page.getPageIndex() > page.getFirstPageIndex()) {
			pageContext.setAttribute("isPrevPageAvailable", new Boolean(true));
		} else {
			pageContext.setAttribute("isPrevPageAvailable", new Boolean(false));
		}
		
		
		// get the parent pagination
		Object wrapper = pageContext.getAttribute(parent.getId());
		if (logger.isLoggable(Level.FINE)) {
			logger.fine("Is PrevPage Available : "+ pageContext.getAttributesScope("isPrevPageAvailable"));
		}
		
		if (wrapper instanceof GenericWebSortByPaginationWrapper) {
			GenericWebSortByPaginationWrapper webWrapper = (GenericWebSortByPaginationWrapper)wrapper;
			pageContext.setAttribute("prevPageUrl",webWrapper.getPrevPageUrl());
		} 		
		else if (wrapper instanceof GenericWebPaginationWrapper) {
			GenericWebPaginationWrapper webWrapper = (GenericWebPaginationWrapper)wrapper;
			pageContext.setAttribute("prevPageUrl",webWrapper.getPrevPageUrl());


		}
		return Tag.EVAL_BODY_INCLUDE;
	}
	
	
}
